package l.l.w.leetcode.LongestValidParentheses;

import java.util.LinkedList;
import java.util.Scanner;
import java.util.Stack;

/**
 * Created by llw on 2017/11/5.
 */
public class LongestValidParentheses {

    public int longestValidParentheses(String s) {
        if(s==null || s.length()<2) return 0;

        int length = 0;
        int maxLength = 0;
        for(int i =0 ; i < s.length(); ++i){
            int[] res = findValidParentheses(s,i);
            if(res[0]> maxLength) maxLength = res[0];
            i=res[1];
        }
        return maxLength;
    }

    private int[] findValidParentheses(String s, int i) {
        Stack<Node> stack = new Stack<>();
        int len=0;
        int start = i;
        for(; i< s.length();++i){
            char c = s.charAt(i);
            if(c =='('){
                stack.push(new Node('(',i));
            }else{
                if(stack.isEmpty()){
                    return new int[]{i-start,i};
                }else{
                    stack.pop();
                    len+=2;
                }
            }
        }
        if(! stack.isEmpty()){
            if(stack.firstElement().index != start){
                return new int[]{stack.firstElement().index - start,stack.firstElement().index};
            }else{
                return new int[]{len,s.length()-1};

            }
        }else{
            return new int[]{len,s.length()-1};
        }
    }
    class Node{
        char c;
        int index;
        Node(char c,int index){
            this.c = c;
            this.index = index;
        }
    }

    public static void main(String[] args) {
        String s = "(()(((()";
        int result = new LongestValidParentheses().longestValidParentheses(s);
        System.out.println(result);
    }
}
